<template>
    <div>
        <div class="section">
            <div class="location">
                <span>当前位置：</span>
                <a href="/index.html">首页</a> &gt;
                <a href="/cart.html">购物车</a>
            </div>
        </div>

        <div class="section">
            <div class="wrapper">
                <div class="bg-wrap">
                    <!--购物车头部-->
                    <div class="cart-head clearfix">
                        <h2>
                            <i class="iconfont icon-cart"></i>我的购物车</h2>
                        <div class="cart-setp">
                            <ul>
                                <li class="first active">
                                    <div class="progress">
                                        <span>1</span>
                                        放进购物车
                                    </div>
                                </li>
                                <li>
                                    <div class="progress">
                                        <span>2</span>
                                        填写订单信息
                                    </div>
                                </li>
                                <li class="last">
                                    <div class="progress">
                                        <span>3</span>
                                        支付/确认订单
                                    </div>
                                </li>
                            </ul>
                        </div>
                    </div>
                    <!--购物车头部-->
                    <!--商品列表-->
                    <div class="cart-box">
                        <input id="jsondata" name="jsondata" type="hidden">
                        <table width="100%" align="center" class="cart-table" border="0" cellspacing="0" cellpadding="8">
                            <tbody>
                                <tr>
                                    <th width="48" align="center">
                                        <a>选择</a>
                                    </th>
                                    <th align="left" colspan="2">商品信息</th>
                                    <th width="84" align="left">单价</th>
                                    <th width="104" align="center">数量</th>
                                    <th width="104" align="left">金额(元)</th>
                                    <th width="54" align="center">操作</th>
                                </tr>
                                <tr v-for='item in goodsList' :key='item.id'>
                                    <th width="48" align="center">
                                        <el-switch
                                            v-model="item.isSelected"
                                            active-color="#409eff"
                                            inactive-color="#555">
                                        </el-switch>
                                    </th>
                                    <th align="left" colspan="2">
                                        <div>
                                            <img style="width:50px;height:50px;margin-right=10px" :src="item.img_url" alt="">
                                            <span>{{item.title}}</span>
                                        </div>
                                    </th>
                                    <th width="84" align="left">{{item.sell_price}}</th>
                                    <th width="104" align="center">
                                        <inputNumber @getCountChange="goodsCountChange" :goodsCount='item.buycount' :goodsId='item.id'></inputNumber>
                                        
                                        </th>
                                    <th width="104" align="left">{{item.sell_price * item.buycount}}</th>
                                    <th width="54" align="center">
                                        <a @click='deleteGoodsById(item.id)' href="javascript:void(0)">删除</a>
                                    </th>
                                </tr>
                                <tr v-if='goodsList.length==0'>
                                    <td colspan="10">
                                        <div class="msg-tips">
                                            <div class="icon warning">
                                                <i class="iconfont icon-tip"></i>
                                            </div>
                                            <div class="info">
                                                <strong>购物车没有商品！</strong>
                                                <p>您的购物车为空，
                                                    <a href="/index.html">马上去购物</a>吧！</p>
                                            </div>
                                        </div>
                                    </td>
                                </tr>
                                <tr>
                                    <th align="right" colspan="8">
                                        已选择商品
                                        <b class="red" id="totalQuantity">{{getTotalCount}}</b> 件 &nbsp;&nbsp;&nbsp; 商品总金额（不含运费）：
                                        <span class="red">￥</span>
                                        <b class="red" id="totalAmount">{{getTotalAmount}}</b>元
                                    </th>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                    <!--/商品列表-->
                    <!--购物车底部-->
                    <div class="cart-foot clearfix">
                        <div class="right-box">
                            <button @click='continueBuy' class="button" >继续购物</button>
                            <button @click="goToOrder" class="submit">立即结算</button>
                        </div>
                    </div>
                    <!--购物车底部-->
                </div>
            </div>
        </div>

    </div>
</template>


<script>
import { getLocalObj } from "../../common/localStorageHelper.js";
import inputNumber from "../subcomponents/inputnumber";

export default {
  data() {
    return {
      goodsList: []
    };
  },
  components: {
    inputNumber
  },
  computed: {
    getTotalCount() {
      let totalCount = 0;
      this.goodsList.forEach(item => {
        if (item.isSelected) {
          totalCount += item.buycount;
        }
      });
      return totalCount;
    },
    getTotalAmount() {
      let totalAmount = 0;
      this.goodsList.forEach(item => {
        if (item.isSelected) {
          totalAmount += item.buycount * item.sell_price;
        }
      });
      return totalAmount;
    }
  },
  created() {
    this.getGoodsInfo();
  },
  methods: {
    async getGoodsInfo() {
      const LocalObj = getLocalObj();
      // console.log(LocalObj);
      const tempArr = [];
      for (const key in LocalObj) {
        tempArr.push(key);
      }
      const url = `site/comment/getshopcargoods/${tempArr.join(",")}`;
      // console.log(url);

      const response = await this.$axios.get(url)
      response.data.message.forEach(item => {
          item.buycount = LocalObj[item.id];
          item.isSelected = true;
        });
        this.goodsList = response.data.message;

    //   this.$axios.get(url).then(response => {
    //     // console.log(response.data);
    //     response.data.message.forEach(item => {
    //       item.buycount = LocalObj[item.id];
    //       item.isSelected = true;
    //     });
    //     this.goodsList = response.data.message;
    //   });
    },
    goodsCountChange(goods) {
      // console.log(goods);//{goodsId: 91, count: 6}
      this.goodsList.forEach(item => {
        if (item.id == goods.goodsId) {
          item.buycount = goods.count;
        }
      });
      this.$store.commit("updateGoods", goods);
    },
    deleteGoodsById(goodsId) {
      this.$confirm(`是否删除id为 ${goodsId} 的商品吗?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          const index = this.goodsList.findIndex(item => {
            return item.id == goodsId;
          });

          //删除索引对应的数据
          this.goodsList.splice(index, 1);

          //调用Vuex中根据id删除商品的方法
          this.$store.commit("deleteGoodsById", goodsId);
        })
        .catch(() => {
          console.log("...取消了...");
        });
    },
    continueBuy() {
      this.$router.push({ path: "/site/goodslist" });
    },
    goToOrder() {
      const tempArr = [];
      console.log(this.goodsList);
      
      this.goodsList.forEach(item => {
        if (item.isSelected) {
          tempArr.push(item.id);
        }
      });
      if (tempArr.length == 0) {
        this.$message({
          message: "请至少选择一件商品来下单",
          type: "warning"
        });
        return ;
      }
      this.$router.push({path:`/site/order/${tempArr.join(',')}`})
    }
  }
}
</script>